QteaTensor with Abelian symmetry
Abelian symmetry tensor class
- class qredtea.symmetries.abeliantensor.AbelianSymmetryInjector[source]
Provide a way to inject parsing of symmetry, i.e., generator, trivial symmetries etc.
- inject_parse_sectors(params, sym)[source]
Parse sectors for symmetry and update symmetry if necessary.
Arguments
- paramsdict
Dictionary with simulation params, of interest are here the keys SymmetryTypes and Symmetries.
Returns
sym :
AbelianSymCombinedGroup- sectorsdict
Dictionary with positions as key and irreps as values.
Details
The position is hard-coded for the TTN at the moment.
- class qredtea.symmetries.abeliantensor.QteaAbelianTensor(links, ctrl='N', are_links_outgoing=None, base_tensor_cls=<class 'qtealeaves.tensors.tensor.QteaTensor'>, dtype=None, device=None, requires_grad=None)[source]
Abelian tensor for Quantum Tea simulations.
Arguments
- linkslist of
AbelianSymLinkinstances Specifies the links in the tensor.
- ctrlstr, optional
Initialization of tensor, either “N” (empty tensor without coupling sectors), “R”, “random” (random), Default to “N” Valid data type for the underlying tensors.
- are_links_outgoinglist of bools
Used in symmetric tensors only: direction of link in tensor. Length is same as rank of tensor. Default of None will raise exception.
- base_tensor_clsvalid dense quantum tea tensor or None
Used in symmetric tensors only: class representing dense tensor Default to
QteaTensor
dtype : data type, optional
device : device specification, optional
- requires_grad: specification if requires an autograd function, not supported here
Default do None
- add_update(other, factor_this=None, factor_other=None)[source]
Inplace addition as self = factor_this * self + factor_other * other.
- property are_links_outgoing
Define property of outgoing links as property (always False).
- assert_unitary(links, tol=1e-07)[source]
Raise error if tensor is not unitary up to tolerance for given links. Arguments ————- links : list of int
Indices of links over which which we test unitarity.
- attach_dummy_link(position, is_outgoing=True)[source]
Attach dummy link at given position (inplace update).
- property base_tensor_cls
Base tensor class.
- classmethod blocks_as_matrix(links, are_links_outgoing, first_column, tensor_backend)[source]
Build a block-diagonal matrix from consecutive links. The off-diagonal blocks are truncated.
Arguments
- linkslist
List of links.
- are_links_outgoinglist[bool]
Specifies if the links of the matrix are outgoing.
- first_columnint
The index of the first first column where the rows are links[:first_column] and the columns are link[first_column:]
- conj_update()[source]
Apply the complex conjugated to the tensor in place (including flip directions).
- convert(dtype=None, device=None, stream=None)[source]
Convert underlying array to the specified data type inplace.
- static convert_operator_dict(op_dict, symmetries=None, generators=None, base_tensor_cls=<class 'qtealeaves.tensors.tensor.QteaTensor'>)[source]
Convert an operators dict from base tensors to symmetric tensors.
- property device
Device where the tensor is stored.
- property dtype
Data type of the underlying arrays.
- property dtype_eps
Data type’s machine precision of the underlying arrays.
- eig_api(matvec_func, links, conv_params, args_func=None, kwargs_func=None)[source]
Interface to hermitian eigenproblem
Arguments
- matvec_funccallable
Mulitplies “matrix” with “vector”
- linkslinks according to
QteaTensor Contain the dimension of the problem.
- conv_paramsinstance of
TNConvergenceParameters Settings for eigenproblem with Arnoldi method.
args_func : arguments for matvec_func
kwargs_func : keyword arguments for matvec_func
Returns
eigenvalues : scalar
eigenvectors : instance of
QteaAbelianTensor
- eig_api_qtea(matvec_func, conv_params, args_func=None, kwargs_func=None, injected_funcs=None)[source]
Interface to hermitian eigensolver via qtealeaves’ solver.
- eigh()[source]
Compute eigenvalues and eigenvectors of a two-leg hermitian tensor. Not implemented for AbelianTensor.
- einsum(einsum_str, *others)[source]
Call to einsum with self as first tensor (not implemented).
Arguments
- einsum_strstr
Einsum contraction rule.
- others: List[
QteaAbelianTensors] 2nd, 3rd, …, n-th tensor in einsum rule as positional arguments.
Results
- tensor
QteaAbelianTensor Contracted tensor according to the einsum rules.
Details
The call
np.einsum(einsum_str, x.elem, y.elem, z.elem)translates intox.einsum(einsum_str, y, z)for x, y, and z beingQteaAbelianTensor.
- expand_link_tensorpair(other, link_self, link_other, new_dim)[source]
Expand randomly the link between a pair of tensors.
Arguments
other : instance of :class`QteaAbelianTensor`
- link_selfint
Expand this link in self
- link_otherint
Expand this link in other. Link must be a match (dimension etc.)
Returns
- new_thisinstance of :class`QteaAbelianTensor`
Expanded version of self
- new_otherinstance of :class`QteaAbelianTensor`
Expanded version of other
- eye_like(link)[source]
Generate identity matrix.
Arguments
- selfinstance of
QteaTensor Extract data type etc from this one here.
- linksame as returned by links property, here AbelianSymLink.
Dimension of the square, identity matrix.
- selfinstance of
- fuse_links_update(fuse_low, fuse_high, is_link_outgoing=True)[source]
Fuses one set of links to a single link (inplace-update, no unfuse information).
- get_all_subtensors()[source]
Returns a list of subtensors of self. For symmetric tensors list all self.degeneracy_tensors. For non-symmetric tensors this is just self.elem.
- is_implemented_device(query)[source]
Check if argument query is an implemented device via base tensor.
Parameters
- querystr
String to be tested if it corresponds to a device implemented with this tensor.
Returns
- is_implementedbool
True if string is available as device.
- property linear_algebra_library
Specification of the linear algebra library used as string numpy-cupy`.
- property links
Returns list of
AbelianSymLinkinstances.
- matmul(other: _AbstractQteaTensor) QteaAbelianTensor[source]
Concrete implementation of batched matrix multiplication for QteaAbelianTensor.
Parameters
- other_AbstractQteaTensor
Tensor with compatible shape for multiplication.
Returns
- QteaAbelianTensor
New Tensor representing the (batched) matrix product.
- matrix_function(first_column, function_attr_str, **func_kwargs)[source]
Apply a matrix function to the rank-n tensor by reshaping it into a bipartition of legs. Result of matrix function must be exactly one matrix of the same size. This is not an inplace function.
Details
Currently, we support the following functions:
expm to take the matrix exponential
q_from_qr to generate unitary matrices
copy as identity operation.
Arguments
- first_columnint
The first first_column legs will constitute the left link of a matrix.
- function_attr_strstr
Which matrix function to perform, see above the available implementations.
Return
- ftensortensor
The tensor after applying the function, shape the same as initial tensor.
- classmethod mpi_recv(from_, comm, tensor_backend)[source]
Send tensor via MPI.
Arguments
- from_integer
MPI process to receive tensor from.
comm : instance of MPI communicator to be used
tensor_backend : instance of
TensorBackend
- property ndim
Rank of the tensor.
- random_unitary(links)[source]
Generate a random unitary matrix via performing a SVD on a random tensor, where a matrix dimension is specified with links.
- randomize(noise=None)[source]
Randomizes the entries of self. Preserves the structure of symmetry blocks.
Arguments
- noisefloat | None
The amount of noise added. None randomizes completely.
- classmethod read(filehandle, dtype, device, base_tensor_cls, cmplx=True, order='F')[source]
Read a tensor from file.
- classmethod read_pickle(filename)[source]
Read via pickle module.
Arguments
- filenamestr or similar
File where tensor is stored.
Returns
QteaAbelianTensorTensor from file.
- restrict_irreps(link_idx, sector)[source]
Restrict, i.e., project, link to a sector
Arguments
- link_idxint
Restrict, i.e., project out, symmetry sectors on this link.
- sectorirreps
Irreps to be kept, allows for multiple ones.
Returns
QteaAbelianTensorNew tensor based on self with restricted irreps on link_idx-th link according to sector.
Raises
QRedTeaEmptyTensorErrorFor restricting irreps, we throw an error if an empty tensor is generated.
- save_pickle(filename)[source]
Save class via pickle module.
Arguments
- filenamestr
If extension matches, tensor is stored under this filename. Otherwise, file extension is added.
- scale_link(link_weights, link_idx)[source]
Scale tensor along one link at link_idx with weights.
Arguments
- link_weightsinstance of
AbelianSymLinkWeight Scalar weights, e.g., singular values.
- link_idxint
Link which should be scaled.
Returns
updated_link : instance of
QteaTensor- link_weightsinstance of
- scale_link_update(link_weights, link_idx)[source]
Scale tensor along one link at link_idx with weights (inplace update).
Arguments
- link_weightsinstance of
AbelianSymLinkWeight Scalar weights, e.g., singular values.
- link_idxint
Link which should be scaled.
- link_weightsinstance of
- set_diagonal_entry(position, value)[source]
Set the diagonal element in a rank-2 tensor (inplace update)
- set_matrix_entry(idx_row, idx_col, value)[source]
Set one element in a rank-2 tensor (inplace update)
- static set_missing_link(links, max_dim, are_links_outgoing=None, restrict_irreps=None)[source]
Calculate the property of a missing link in a list.
Arguments
- linkslist of instances of
AbelianSymLink Contains data like returned by property links, except for one element being None
- max_dimint
Maximal dimension of link allowed by convergence parameters or similar.
- are_links_outgoinglist of bools
Indicates link direction for symmetry (required here).
- restrict_irreps
IrrepListing| None, optional All irreps from here will remain in the link. Irreps which are here but not in the link, will not be added. Degeneracies will be calculated based on the minimum of the two. Default to None.
- linkslist of instances of
- property shape
Dimension of tensor along each dimension.
- split_link_deg_charge(link_idx)[source]
Split a link into two, where one carries the degeneracy, the other the charge. Documentation see
_AbstractQteaTensor.
- split_qr(legs_left, legs_right, perm_left=None, perm_right=None, is_q_link_outgoing=True, disable_streams=False)[source]
Split the tensor via a QR decomposition.
Parameters
- selfinstance of
QteaTensor Tensor upon which apply the SVD
- legs_leftlist of int
Legs that will compose the rows of the matrix
- legs_rightlist of int
Legs that will compose the columns of the matrix
- perm_leftlist of int, optional
permutations of legs after the SVD on left tensor
- perm_rightlist of int, optional
permutation of legs after the SVD on right tensor
- disable_streamsboolean, optional
Can disable streams to avoid nested generation of streams.
Returns
- tens_left: instance of
QteaTensor unitary tensor after the QR, i.e., Q.
- tens_right: instance of
QteaTensor upper triangular tensor after the QR, i.e., R
- selfinstance of
- split_qrte(tens_right, singvals_self, operator=None, conv_params=None, is_q_link_outgoing=True)[source]
Split via a truncated expanded QR.
- split_rq(legs_left, legs_right, perm_left=None, perm_right=None, is_q_link_outgoing=True)[source]
Split the tensor via a RQ decomposition. The abstract class defines the RQ via a QR and permutation of legs, but we highly recommend overwriting this approach with an actual RQ.
Parameters
- selfinstance of
_AbstractQteaTensor Tensor upon which apply the RQ
- legs_leftlist of int
Legs that will compose the rows of the matrix (and the R matrix)
- legs_rightlist of int
Legs that will compose the columns of the matrix (and the Q matrix)
- perm_leftlist of int | None, optional
permutations of legs after the QR on left tensor Default to None (no permutation)
- perm_rightlist of int | None, optional
permutation of legs after the QR on right tensor Default to None (no permutation)
- is_q_link_outgoingint, optional
Direction of link, placeholder for symmetric tensors. Default to True.
Returns
- tens_left: instance of
_AbstractQteaTensor upper triangular tensor after the RQ, i.e., R
- tens_right: instance of
_AbstractQteaTensor unitary tensor after the RQ, i.e., Q.
- selfinstance of
- split_svd(legs_left, legs_right, perm_left=None, perm_right=None, contract_singvals='N', conv_params=None, is_link_outgoing_left=True, no_truncation=False, disable_streams=False)[source]
Perform a truncated Singular Value Decomposition by first reshaping the tensor into a legs_left x legs_right matrix, and permuting the legs of the ouput tensors if needed. If the contract_singvals = (‘L’, ‘R’) it takes care of renormalizing the output tensors such that the norm of the MPS remains 1 even after a truncation.
Parameters
- selfinstance of
QteaAbelianTensor Tensor upon which apply the SVD
- legs_leftlist of int
Legs that will compose the rows of the matrix
- legs_rightlist of int
Legs that will compose the columns of the matrix
- perm_leftlist of int, optional
permutations of legs after the SVD on left tensor
- perm_rightlist of int, optional
permutation of legs after the SVD on right tensor
- contract_singvals: string, optional
- How to contract the singular values.
‘N’ : no contraction ‘L’ : to the left tensor ‘R’ : to the right tensor
- conv_params
TNConvergenceParameters, optional Convergence parameters to use in the procedure. If None is given, then use the default convergence parameters of the TN. Default to None.
- no_truncationboolean, optional
Allow to run without truncation Default to False (hence truncating by default)
- disable_streamsboolean, optional
Can disable streams to avoid nested generation of streams.
Returns
- tens_left: instance of
QteaAbelianTensor left tensor after the SVD
- tens_right: instance of
QteaAbelianTensor right tensor after the SVD
- singvals:
AbelianSymLinkWeights singular values kept after the SVD
- singvals_cut:
AbelianSymLinkWeights singular values cut after the SVD, normalized with the biggest singval
- selfinstance of
- squeeze_update(position=None)[source]
Remove link at given position if dimension is one (inplace update).
Parameters
- positionint | tuple[int, …] | None, optional
Position(s) of the link(s) to be squeezed, by default None i.e. all links with dimension one are squeezed.
- stack_first_and_last_link(other)[source]
Stack first and last link of tensor targeting MPS addition (not implemented).
- stack_link(other, link)[source]
Stack two tensors along a given link.
Arguments
- otherinstance of
QteaAbelianTensor Links must match self up to the specified link.
- linkinteger
Stack along this link.
Returns
new_this : instance of :class:QteaAbelianTensor`
- otherinstance of
- stream(disable_streams=False)[source]
Get the instance of a context which can be used to parallelize. Symmetric tensors always go via the base tensor class.
Parameters
- disable_streamsbool, optional
Allows to disable streams to avoid nested creation of streams. Globally, streams should be disabled via the set_streams_* function of the corresponding base tensor module. Default to False.
Returns
Context manager, e.g.,
Streamif running on GPU and enabled ornullcontext(AbstractContextManager)otherwise.
- tensordot(other, contr_idx, disable_streams=False)[source]
Tensor contraction of two tensors along the given indices.
- to_dense(true_copy=False)[source]
Return dense tensor (if true_copy=False, same object may be returned).
- linkslist of
- qredtea.symmetries.abeliantensor.default_abelian_backend(device='cpu', dtype=<class 'numpy.complex128'>)[source]
Generate a default tensor backend for symmetric tensors, i.e., with a
QteaTensor.Arguments
- dtypedata type, optional
Data type for numpy or cupy. Default to np.complex128
- devicedevice specification, optional
Default to “cpu”. Available: “cpu”, “gpu”
Returns
tensor_backend :
TensorBackend
Abelian links and link weights for qtealeaves module.
- class qredtea.symmetries.abelianlinks.AbelianSymLink(sym, irrep_listing)[source]
Arguments
sym : instance of AbelianSymCombinedGroup
irrep_listing : instance of IrrepListing
- classmethod create_dummy(sym)[source]
Create a dummy link with the identical irrep.
Argument
sym : instance of AbelianSymCombinedGroup
- classmethod from_link_list(links, are_links_outgoing=None)[source]
Couple the irreps from a list of links to generate a new link.
Arguments
links : list of AbelianSymLink
- are_links_outgoinglist of boolean, (mandatory here)
Describes the link direction. Default to None, but required here.
- generate_cs(irreps)[source]
Generate the coupling sectors for the link through the passed irreps which are active.
Arguments
- irrepsnp.ndarray, rank-2, int-type
active irreps, unsorted, non-unique allowed Unsorted because of original order in degeneracy tensors list.
Returns
- csnp.ndarray, rank-1
Coupling sector indices of irreps in link, ordered ascendingly.
- degeneraciesnp.ndarray, rank-1
Degeneracies, same order as cs.
- indsvector
For ordering incoming irreps the same as information in cs. Result of argsort.
- static generate_fuse_rule(cs_fused, degeneracies, inds, cs_links)[source]
Fuse rule is a helper to fuse and unfuse two links.
Arguments
- cs_fusednp.ndarray, (arbitrary rows, one column)
Fused coupling sector. Sorted.
- degeneraciesnp.ndarray / list of ints
Contains the degeneracies of each of the fused CS in cs_fused[inds].
- indsnp.ndarray, rank-1
Contains the output from argsort to sort the entries in degeneracies or cs_links
- cs_linksnp.ndarray of rank-2
Contains the coupling sectors before fusing. Unsorted.
Details
The fuse rule is a dictionary containing
A dictionary accessible with the key deg. The dictionary contains the degeneracy based on the key of the new coupling sector.
The other keys in the main dictionary are the tuples of the (old) coupling sectors. Each entry contains the new coupling sector, and the lower and upper index of the subtensors within the fused tensor, and the dimensions of the original subtensor.
Higher-level functions can add an entry “link” with a link representing the degeneracy dimension after a qr-like decomposition, i.e., the minimum of the matrix dimensions.
- helper_split(other)[source]
Helps with splitting a tensor via decompositions. Will adapt the degneracy dimension to the minimum of both as valid in QR and SVD. Inplace update.
Arguments
other : instance of AbelianSymLink
- property irrep_listing
Irrep listing property.
- product_couple(other, invert_self=False, invert_other=False)[source]
Build all possible combinations of irreps between the link and another link.
Arguments
- otherinstance of AbelianSymLink
Second link where we iterate over all irreps in link.
- invert_selfbool, optional
Flag if irreps on self should be inverted. Default to False
- invert_otherbool, optional
flag if irreps on other should be inverted. Default to False
- random_expand(full_link, target_dim)[source]
Returns link with degeneracies to be added for random expansion to current link.
- restrict_irreps(irrep_listing)[source]
Restrict the irreps in the link to the irreps passed. Degeneracies are also restricted. Update is inplace.
Arguments
- irrep_listinginstance of IrrepListing or None
All irreps from here will remain in the link. Irreps which are here but not in the link, will not be added. Degeneracies will be calculated based on the minimum of the two.
- sanity_check(require_trivial_removed=False)[source]
Run small checks to ensure nothing obvious is broken.
- select_irreps(inds, do_return_deg=False)[source]
Select and return the irreps at given indices.
Arguments
- indsint
Return irreps of selected indices
- do_return_degbool, optional
If true, in addition to irreps the degeneracies are returned as second return value. Default to false.
- property shape
Dimension of the link summing up the degneracy dimensions.
- stack_link(other)[source]
Stacking link executes an union of the underlying irreps returning a new link.
- property sym
Symmetry property which must be equal to the irreps’ symmetry.
- class qredtea.symmetries.abelianlinks.AbelianSymLinkWeight(link, sectors, link_weights, base_tensor_cls, allow_empty=False)[source]
Diagonal matrix for symmetric tensors, i.e., a link weight.
Arguments
link : instance of
AbelianSymLinksectors : integer array, rank-2
link_weights : list of arrays with weights, same order as cs.
- base_tensor_clstype
Contains the base tensor class to perform default operations.
Coupling sectors module.
- class qredtea.symmetries.couplingsectors.CouplingSectors(sectors, sorted_for=None)[source]
Coupling sectors are defined over a given set of links and their irreps. A coupling sector for one link is the index of the corresponding irrep, i.e., a matching coupling sector means matching irrep.
Arguments
- sectorsnp.ndarray of rank-2
First index loops of coupling sectors. Second index loops over links. A rank-3 tensor with 10 subtensors should have dimensions 10 x 3.
- sorted_forinteger list or None, optional
Indicate if coupling sectors are already sorted for a list of links. Default to None (not sorted for any links).
- attach_dummy_link(position)[source]
Attach a dummy link, i.e., coupling sector zero. Inplace update.
- depreceated_iter_tracker_skipped()[source]
Iterate over all row-indices and coupling sectors where tracker is false.
- iter_tracker_accessed()[source]
Iterate over all row-indices and coupling sectors where tracker is true.
- iter_tracker_false()[source]
Iterate over all row-indices and coupling sectors where tracker is false.
- property num_coupling_sectors
Number of coupling sectors.
- remove_dummy_link(position)[source]
Remove dummy link at given position; required to be zero. Inplace update.
- sanity_check()[source]
Checking validity of
CouplingSectors.
- transpose(permutation)[source]
Permute the columns of a CS and return new
CouplingSectors.
Irrep listing module.
- class qredtea.symmetries.irreplistings.IrrepListing(sym, irreps, degeneracies, are_sorted=False, remove_trivial=False, are_unique=False)[source]
IrrepListing contains a list of irreps.
Arguments
- syminstance of
AbelianSymCombinedGroup Combined symmetry group of the irreps.
- irrepsinteger array, rank-2
Irreps as integer labels. Each row contains one irrep. (For projectors, we allow floats. It has to be explicitly allowed in
from_irrepsviaallow_dtype_float=True. The equal sign accepts these including a wildcard NaN matching any irreps.)- degeneraciesinteger array, rank-1
Degenercy of each irrep label.
- are_sortedboolean, optional
Flag if irreps are already sorted. Default to False
- remove_trivialboolean, optional
Flag if trivial irreps with degeneracy equal to zero should be removed. Default to False
- are_uniqueboolean, optional
Flag if irreps are already unique, if not duplicates will be removed and the degeneracy dimension summed up. Default to False.
- static argsort_irreps(irreps)[source]
Argsort similar to numpy’s argsort for and irreps array.
Arguments
- irrepsinteger array, rank-2
Irreps to be sorted row-by-row.
Returns
- indsinteger array, rank-1
Such that irreps[inds, :] sorts the irreps ascendingly.
- classmethod from_irreps(sym, irreps, degeneracies, are_sorted=False, remove_trivial=False, are_unique=False, allow_dtype_float=False)[source]
Generate instance of IrrepListing through irreps and degeneracies.
- property has_degeneracies
Flag if degeneracies exist in the irrep listing.
- index(irrep, start_idx=0, require_match=False)[source]
Search of irrep similar to index method of a python list.
Arguments
- irrepinteger array, rank-1
Search this irrep and return its index in irrep listing.
- start_idxint, optional
Speed-up search by specifying start index if it is known that irrep is not contained in indices (0 … start_idx - 1). Default to 0 (searching complete irrep listing until match)
Returns
- idxint or None
Returns row of match or None if no match given.
- intersection(other, deg_func=<ufunc 'minimum'>)[source]
Intersection of an irrep listing with another irrep listing.
Arguments
- otherinstance of
IrrepListing Second irrep listing to build intersection.
Returns
- irrep_listinginstance of
IrrepListing Contains the common irreps in self and other. Degneracy is build by taking the minimum.
- otherinstance of
- static is_equal_irrep(irrep_a, irrep_b)[source]
Check if two irreps (integer array, rank-1) are equal.
- static is_greater_irrep(irrep_a, irrep_b)[source]
Check if irrep_a is greater than irrep_b (integer array, rank-1).
- static is_smaller_irrep(irrep_a, irrep_b)[source]
Check if irrep_a is smaller than irrep_b (integer array, rank-1).
- iter_matches(other)[source]
Iteration of the matche of an irrep listing with another irrep listing by their integer indices
Arguments
- otherinstance of
IrrepListing Search for matches between self and irrep listing other
Returns
- (ii, jj)
ii is index of matching irrep in self jj is index of matching irrep in other Iterator yields matches in pairs via loop.
- otherinstance of
- static mask_non_unique(irreps, degeneracies)[source]
Modify irrep listing such that only unique irreps are present.
Details
Degeneracy dimension is additive. Update is inplace.
- static mask_trivial(irreps, degeneracies)[source]
Inplace-update masking all trivial irreps with deneracy zero.
- product_couple(other, invert_self=False, invert_other=False)[source]
Build all combinations of irreps and couple them.
Arguments
- otherinstance of
IrrepListing Second set of irreps and degeneracies. Fast-moving index.
- invert_1boolean, optional
Flag if irreps in self should be inverted. Default to False
- invert_2boolean, optional
Flag if irreps in other should be inverted. Default to False
Returns
irrep_listing : instance of
IrrepListingDetails
Method is the equivalent of itertools.product for two irreps. Degeneracies are the product between degeneracy of irrep in self and other.
- otherinstance of
- union(other)[source]
Union of an irrep listing with another irrep listing.
Arguments
- otherinstance of
IrrepListing Second irrep listing to build union.
Returns
- irrep_listinginstance of
IrrepListing Contains the irreps of self and other Degeneracy is sum of degeneracy in self and in other if irreps appears in both.
- otherinstance of
- syminstance of
Symmetry groups defined the Abelian symmetries and combined Abelian symmetry groups.
- class qredtea.symmetries.symmetrygroups.AbelianSymCombinedGroup(*args)[source]
List of one or multiple Abelian symmetries used within a simulation.
- couple_irreps(irrep1, irrep2)[source]
Couple the irreps passed as argument according to the symmetry’s rule.
Arguments
- irrep1integer array
either single irrep (rank-1) or multiple (rank-2)
- irrep2integer array
either single irrep (rank-1) or multiple (rank-2)
- decouple_irreps(irrep1, irrep2)[source]
Decouple the irreps passed as argument according to the symmetry’s rule.
Arguments
- irrep1integer array
either single irrep (rank-1) or multiple (rank-2)
- irrep2integer array
either single irrep (rank-1) or multiple (rank-2)
- property identical_irrep
Identical irrep which does not change charge / sector.
- invert_irrep(irrep)[source]
Invert the irrep passed as argument according to the symmetry’s rule.
Arguments
- irrepinteger array
either single irrep (rank-1) or multiple (rank-2)
- product_couple_irreps(irreps1, irreps2, invert_1=False, invert_2=False)[source]
Build all combinations of irreps and couple them.
Arguments
- irreps1integer array, rank-2
First set of irreps.
- irreps2integer array, rank-2
Second set of irreps. Fast-moving index.
- invert_1boolean, optional
Flag if irreps1 should be inverted. Default to False
- invert_2boolean, optional
Flag if irreps2 should be inverted. Default to False
Returns
irreps : integer arrray, rank-2
Details
Method is the equivalent of itertools.product for two irreps.
- class qredtea.symmetries.symmetrygroups.AbelianSymU1(sym: str = 'U1')[source]
Abelian symmetry of U(1) group.
Arguments
No arguments.
- couple_irrep(irrep1, irrep2)[source]
Couple the two irreps passed as argument according to the symmetry’s rule.
- decouple_irrep(irrep1, irrep2)[source]
Decouple the two irreps passed as argument according to the symmetry’s rule.
- property identical_irrep
Identical irrep which does not change charge / sector.
- class qredtea.symmetries.symmetrygroups.AbelianSymZN(order: int, sym: str = 'Zn')[source]
Abelian symmetry of Zn group.
Arguments
- orderint
Order of the Zn symmetry, i.e., possible irreps range from 0 to (order - 1).
- couple_irrep(irrep1, irrep2)[source]
Couple the two irreps passed as argument according to the symmetry’s rule.
- decouple_irrep(irrep1, irrep2)[source]
Decouple the two irreps passed as argument according to the symmetry’s rule.
- property identical_irrep
Identical irrep which does not change charge / sector.
Integer and boolean arrays for symmetries wrap code to ensure integer only arrays for symmetries in the qtealeaves module.
- qredtea.symmetries.ibarrays.bmaskf(shape)[source]
Create boolean array of zeros / false.
Arguments
- shapeints
Dimensions of the array.
- qredtea.symmetries.ibarrays.bmaskt(shape)[source]
Create boolean array of ones / true.
Arguments
- shapeints
Dimensions of the array.
- qredtea.symmetries.ibarrays.iall(a, axis=None, out=None, keepdims=<no value>, *, where=<no value>)
Test whether all array elements along a given axis evaluate to True.
Parameters
- aarray_like
Input array or object that can be converted to an array.
- axisNone or int or tuple of ints, optional
Axis or axes along which a logical AND reduction is performed. The default (
axis=None) is to perform a logical AND over all the dimensions of the input array. axis may be negative, in which case it counts from the last to the first axis.Added in version 1.7.0.
If this is a tuple of ints, a reduction is performed on multiple axes, instead of a single axis or all the axes as before.
- outndarray, optional
Alternate output array in which to place the result. It must have the same shape as the expected output and its type is preserved (e.g., if
dtype(out)is float, the result will consist of 0.0’s and 1.0’s). See ufuncs-output-type for more details.- keepdimsbool, optional
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.
If the default value is passed, then keepdims will not be passed through to the all method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.
- wherearray_like of bool, optional
Elements to include in checking for all True values. See ~numpy.ufunc.reduce for details.
Added in version 1.20.0.
Returns
- allndarray, bool
A new boolean or array is returned unless out is specified, in which case a reference to out is returned.
See Also
ndarray.all : equivalent method
any : Test whether any element along a given axis evaluates to True.
Notes
Not a Number (NaN), positive infinity and negative infinity evaluate to True because these are not equal to zero.
Changed in version 2.0: Before NumPy 2.0,
alldid not return booleans for object dtype input arrays. This behavior is still available vianp.logical_and.reduce.Examples
>>> import numpy as np >>> np.all([[True,False],[True,True]]) False
>>> np.all([[True,False],[True,True]], axis=0) array([ True, False])
>>> np.all([-1, 4, 5]) True
>>> np.all([1.0, np.nan]) True
>>> np.all([[True, True], [False, True]], where=[[True], [False]]) True
>>> o=np.array(False) >>> z=np.all([-1, 4, 5], out=o) >>> id(z), id(o), z (28293632, 28293632, array(True)) # may vary
- qredtea.symmetries.ibarrays.iany(a, axis=None, out=None, keepdims=<no value>, *, where=<no value>)
Test whether any array element along a given axis evaluates to True.
Returns single boolean if axis is
NoneParameters
- aarray_like
Input array or object that can be converted to an array.
- axisNone or int or tuple of ints, optional
Axis or axes along which a logical OR reduction is performed. The default (
axis=None) is to perform a logical OR over all the dimensions of the input array. axis may be negative, in which case it counts from the last to the first axis.Added in version 1.7.0.
If this is a tuple of ints, a reduction is performed on multiple axes, instead of a single axis or all the axes as before.
- outndarray, optional
Alternate output array in which to place the result. It must have the same shape as the expected output and its type is preserved (e.g., if it is of type float, then it will remain so, returning 1.0 for True and 0.0 for False, regardless of the type of a). See ufuncs-output-type for more details.
- keepdimsbool, optional
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.
If the default value is passed, then keepdims will not be passed through to the any method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.
- wherearray_like of bool, optional
Elements to include in checking for any True values. See ~numpy.ufunc.reduce for details.
Added in version 1.20.0.
Returns
- anybool or ndarray
A new boolean or ndarray is returned unless out is specified, in which case a reference to out is returned.
See Also
ndarray.any : equivalent method
all : Test whether all elements along a given axis evaluate to True.
Notes
Not a Number (NaN), positive infinity and negative infinity evaluate to True because these are not equal to zero.
Changed in version 2.0: Before NumPy 2.0,
anydid not return booleans for object dtype input arrays. This behavior is still available vianp.logical_or.reduce.Examples
>>> import numpy as np >>> np.any([[True, False], [True, True]]) True
>>> np.any([[True, False, True ], ... [False, False, False]], axis=0) array([ True, False, True])
>>> np.any([-1, 0, 5]) True
>>> np.any([[np.nan], [np.inf]], axis=1, keepdims=True) array([[ True], [ True]])
>>> np.any([[True, False], [False, False]], where=[[False], [True]]) False
>>> a = np.array([[1, 0, 0], ... [0, 0, 1], ... [0, 0, 0]]) >>> np.any(a, axis=0) array([ True, False, True]) >>> np.any(a, axis=1) array([ True, True, False])
>>> o=np.array(False) >>> z=np.any([-1, 4, 5], out=o) >>> z, o (array(True), array(True)) >>> # Check now that z is a reference to o >>> z is o True >>> id(z), id(o) # identity of z and o (191614240, 191614240)
- qredtea.symmetries.ibarrays.iargsort(a, axis=-1, kind=None, order=None, *, stable=None)
Returns the indices that would sort an array.
Perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as a that index data along the given axis in sorted order.
Parameters
- aarray_like
Array to sort.
- axisint or None, optional
Axis along which to sort. The default is -1 (the last axis). If None, the flattened array is used.
- kind{‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}, optional
Sorting algorithm. The default is ‘quicksort’. Note that both ‘stable’ and ‘mergesort’ use timsort under the covers and, in general, the actual implementation will vary with data type. The ‘mergesort’ option is retained for backwards compatibility.
Changed in version 1.15.0.: The ‘stable’ option was added.
- orderstr or list of str, optional
When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.
- stablebool, optional
Sort stability. If
True, the returned array will maintain the relative order ofavalues which compare as equal. IfFalseorNone, this is not guaranteed. Internally, this option selectskind='stable'. Default:None.Added in version 2.0.0.
Returns
- index_arrayndarray, int
Array of indices that sort a along the specified axis. If a is one-dimensional,
a[index_array]yields a sorted a. More generally,np.take_along_axis(a, index_array, axis=axis)always yields the sorted a, irrespective of dimensionality.
See Also
sort : Describes sorting algorithms used. lexsort : Indirect stable sort with multiple keys. ndarray.sort : Inplace sort. argpartition : Indirect partial sort. take_along_axis : Apply
index_arrayfrom argsortto an array as if by calling sort.
Notes
See sort for notes on the different sorting algorithms.
As of NumPy 1.4.0 argsort works with real/complex arrays containing nan values. The enhanced sort order is documented in sort.
Examples
One dimensional array:
>>> import numpy as np >>> x = np.array([3, 1, 2]) >>> np.argsort(x) array([1, 2, 0])
Two-dimensional array:
>>> x = np.array([[0, 3], [2, 2]]) >>> x array([[0, 3], [2, 2]])
>>> ind = np.argsort(x, axis=0) # sorts along first axis (down) >>> ind array([[0, 1], [1, 0]]) >>> np.take_along_axis(x, ind, axis=0) # same as np.sort(x, axis=0) array([[0, 2], [2, 3]])
>>> ind = np.argsort(x, axis=1) # sorts along last axis (across) >>> ind array([[0, 1], [0, 1]]) >>> np.take_along_axis(x, ind, axis=1) # same as np.sort(x, axis=1) array([[0, 3], [2, 2]])
Indices of the sorted elements of a N-dimensional array:
>>> ind = np.unravel_index(np.argsort(x, axis=None), x.shape) >>> ind (array([0, 1, 1, 0]), array([0, 0, 1, 1])) >>> x[ind] # same as np.sort(x, axis=None) array([0, 2, 2, 3])
Sorting with keys:
>>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')]) >>> x array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')])
>>> np.argsort(x, order=('x','y')) array([1, 0])
>>> np.argsort(x, order=('y','x')) array([0, 1])
- qredtea.symmetries.ibarrays.iarray(array)[source]
Convert the given list or array into an integer array.
Arguments
- arraylist, tuple, ndarray, etc
Content of the integer array to be created.
- qredtea.symmetries.ibarrays.ichoice(a, size=None, replace=True, p=None)
choice(a, size=None, replace=True, p=None)
Generates a random sample from a given 1-D array
Added in version 1.7.0.
Note
New code should use the ~numpy.random.Generator.choice method of a ~numpy.random.Generator instance instead; please see the random-quick-start.
Warning
This function uses the C-long dtype, which is 32bit on windows and otherwise 64bit on 64bit platforms (and 32bit on 32bit ones). Since NumPy 2.0, NumPy’s default integer is 32bit on 32bit platforms and 64bit on 64bit platforms.
Parameters
- a1-D array-like or int
If an ndarray, a random sample is generated from its elements. If an int, the random sample is generated as if it were
np.arange(a)- sizeint or tuple of ints, optional
Output shape. If the given shape is, e.g.,
(m, n, k), thenm * n * ksamples are drawn. Default is None, in which case a single value is returned.- replaceboolean, optional
Whether the sample is with or without replacement. Default is True, meaning that a value of
acan be selected multiple times.- p1-D array-like, optional
The probabilities associated with each entry in a. If not given, the sample assumes a uniform distribution over all entries in
a.
Returns
- samplessingle item or ndarray
The generated random samples
Raises
- ValueError
If a is an int and less than zero, if a or p are not 1-dimensional, if a is an array-like of size 0, if p is not a vector of probabilities, if a and p have different lengths, or if replace=False and the sample size is greater than the population size
See Also
randint, shuffle, permutation random.Generator.choice: which should be used in new code
Notes
Setting user-specified probabilities through
puses a more general but less efficient sampler than the default. The general sampler produces a different sample than the optimized sampler even if each element ofpis 1 / len(a).Sampling random rows from a 2-D array is not possible with this function, but is possible with Generator.choice through its
axiskeyword.Examples
Generate a uniform random sample from np.arange(5) of size 3:
>>> np.random.choice(5, 3) array([0, 3, 4]) # random >>> #This is equivalent to np.random.randint(0,5,3)
Generate a non-uniform random sample from np.arange(5) of size 3:
>>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0]) array([3, 3, 0]) # random
Generate a uniform random sample from np.arange(5) of size 3 without replacement:
>>> np.random.choice(5, 3, replace=False) array([3,1,0]) # random >>> #This is equivalent to np.random.permutation(np.arange(5))[:3]
Generate a non-uniform random sample from np.arange(5) of size 3 without replacement:
>>> np.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0]) array([2, 3, 0]) # random
Any of the above can be repeated with an arbitrary array-like instead of just integers. For instance:
>>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher'] >>> np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3]) array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'], # random dtype='<U11')
- qredtea.symmetries.ibarrays.icumprod(a, axis=None, dtype=None, out=None)
Return the cumulative product of elements along a given axis.
Parameters
- aarray_like
Input array.
- axisint, optional
Axis along which the cumulative product is computed. By default the input is flattened.
- dtypedtype, optional
Type of the returned array, as well as of the accumulator in which the elements are multiplied. If dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used instead.
- outndarray, optional
Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output but the type of the resulting values will be cast if necessary.
Returns
- cumprodndarray
A new array holding the result is returned unless out is specified, in which case a reference to out is returned.
See Also
cumulative_prod : Array API compatible alternative for
cumprod. ufuncs-output-typeNotes
Arithmetic is modular when using integer types, and no error is raised on overflow.
Examples
>>> import numpy as np >>> a = np.array([1,2,3]) >>> np.cumprod(a) # intermediate results 1, 1*2 ... # total product 1*2*3 = 6 array([1, 2, 6]) >>> a = np.array([[1, 2, 3], [4, 5, 6]]) >>> np.cumprod(a, dtype=float) # specify type of output array([ 1., 2., 6., 24., 120., 720.])
The cumulative product for each column (i.e., over the rows) of a:
>>> np.cumprod(a, axis=0) array([[ 1, 2, 3], [ 4, 10, 18]])
The cumulative product for each row (i.e. over the columns) of a:
>>> np.cumprod(a,axis=1) array([[ 1, 2, 6], [ 4, 20, 120]])
- qredtea.symmetries.ibarrays.ikron(a, b)
Kronecker product of two arrays.
Computes the Kronecker product, a composite array made of blocks of the second array scaled by the first.
Parameters
a, b : array_like
Returns
out : ndarray
See Also
outer : The outer product
Notes
The function assumes that the number of dimensions of a and b are the same, if necessary prepending the smallest with ones. If
a.shape = (r0,r1,..,rN)andb.shape = (s0,s1,...,sN), the Kronecker product has shape(r0*s0, r1*s1, ..., rN*SN). The elements are products of elements from a and b, organized explicitly by:kron(a,b)[k0,k1,...,kN] = a[i0,i1,...,iN] * b[j0,j1,...,jN]
where:
kt = it * st + jt, t = 0,...,N
In the common 2-D case (N=1), the block structure can be visualized:
[[ a[0,0]*b, a[0,1]*b, ... , a[0,-1]*b ], [ ... ... ], [ a[-1,0]*b, a[-1,1]*b, ... , a[-1,-1]*b ]]
Examples
>>> import numpy as np >>> np.kron([1,10,100], [5,6,7]) array([ 5, 6, 7, ..., 500, 600, 700]) >>> np.kron([5,6,7], [1,10,100]) array([ 5, 50, 500, ..., 7, 70, 700])
>>> np.kron(np.eye(2), np.ones((2,2))) array([[1., 1., 0., 0.], [1., 1., 0., 0.], [0., 0., 1., 1.], [0., 0., 1., 1.]])
>>> a = np.arange(100).reshape((2,5,2,5)) >>> b = np.arange(24).reshape((2,3,4)) >>> c = np.kron(a,b) >>> c.shape (2, 10, 6, 20) >>> I = (1,3,0,2) >>> J = (0,2,1) >>> J1 = (0,) + J # extend to ndim=4 >>> S1 = (1,) + b.shape >>> K = tuple(np.array(I) * np.array(S1) + np.array(J1)) >>> c[K] == a[I]*b[J] True
- qredtea.symmetries.ibarrays.imax(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
Return the maximum of an array or maximum along an axis.
Parameters
- aarray_like
Input data.
- axisNone or int or tuple of ints, optional
Axis or axes along which to operate. By default, flattened input is used.
Added in version 1.7.0.
If this is a tuple of ints, the maximum is selected over multiple axes, instead of a single axis or all the axes as before.
- outndarray, optional
Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. See ufuncs-output-type for more details.
- keepdimsbool, optional
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.
If the default value is passed, then keepdims will not be passed through to the
maxmethod of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.- initialscalar, optional
The minimum value of an output element. Must be present to allow computation on empty slice. See ~numpy.ufunc.reduce for details.
Added in version 1.15.0.
- wherearray_like of bool, optional
Elements to compare for the maximum. See ~numpy.ufunc.reduce for details.
Added in version 1.17.0.
Returns
- maxndarray or scalar
Maximum of a. If axis is None, the result is a scalar value. If axis is an int, the result is an array of dimension
a.ndim - 1. If axis is a tuple, the result is an array of dimensiona.ndim - len(axis).
See Also
- amin :
The minimum value of an array along a given axis, propagating any NaNs.
- nanmax :
The maximum value of an array along a given axis, ignoring any NaNs.
- maximum :
Element-wise maximum of two arrays, propagating any NaNs.
- fmax :
Element-wise maximum of two arrays, ignoring any NaNs.
- argmax :
Return the indices of the maximum values.
nanmin, minimum, fmin
Notes
NaN values are propagated, that is if at least one item is NaN, the corresponding max value will be NaN as well. To ignore NaN values (MATLAB behavior), please use nanmax.
Don’t use ~numpy.max for element-wise comparison of 2 arrays; when
a.shape[0]is 2,maximum(a[0], a[1])is faster thanmax(a, axis=0).Examples
>>> import numpy as np >>> a = np.arange(4).reshape((2,2)) >>> a array([[0, 1], [2, 3]]) >>> np.max(a) # Maximum of the flattened array 3 >>> np.max(a, axis=0) # Maxima along the first axis array([2, 3]) >>> np.max(a, axis=1) # Maxima along the second axis array([1, 3]) >>> np.max(a, where=[False, True], initial=-1, axis=0) array([-1, 3]) >>> b = np.arange(5, dtype=float) >>> b[2] = np.nan >>> np.max(b) np.float64(nan) >>> np.max(b, where=~np.isnan(b), initial=-1) 4.0 >>> np.nanmax(b) 4.0
You can use an initial value to compute the maximum of an empty slice, or to initialize it to a different value:
>>> np.max([[-50], [10]], axis=-1, initial=0) array([ 0, 10])
Notice that the initial value is used as one of the elements for which the maximum is determined, unlike for the default argument Python’s max function, which is only used for empty iterables.
>>> np.max([5], initial=6) 6 >>> max([5], default=6) 5
- qredtea.symmetries.ibarrays.imin(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
Return the minimum of an array or minimum along an axis.
Parameters
- aarray_like
Input data.
- axisNone or int or tuple of ints, optional
Axis or axes along which to operate. By default, flattened input is used.
Added in version 1.7.0.
If this is a tuple of ints, the minimum is selected over multiple axes, instead of a single axis or all the axes as before.
- outndarray, optional
Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. See ufuncs-output-type for more details.
- keepdimsbool, optional
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.
If the default value is passed, then keepdims will not be passed through to the
minmethod of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.- initialscalar, optional
The maximum value of an output element. Must be present to allow computation on empty slice. See ~numpy.ufunc.reduce for details.
Added in version 1.15.0.
- wherearray_like of bool, optional
Elements to compare for the minimum. See ~numpy.ufunc.reduce for details.
Added in version 1.17.0.
Returns
- minndarray or scalar
Minimum of a. If axis is None, the result is a scalar value. If axis is an int, the result is an array of dimension
a.ndim - 1. If axis is a tuple, the result is an array of dimensiona.ndim - len(axis).
See Also
- amax :
The maximum value of an array along a given axis, propagating any NaNs.
- nanmin :
The minimum value of an array along a given axis, ignoring any NaNs.
- minimum :
Element-wise minimum of two arrays, propagating any NaNs.
- fmin :
Element-wise minimum of two arrays, ignoring any NaNs.
- argmin :
Return the indices of the minimum values.
nanmax, maximum, fmax
Notes
NaN values are propagated, that is if at least one item is NaN, the corresponding min value will be NaN as well. To ignore NaN values (MATLAB behavior), please use nanmin.
Don’t use ~numpy.min for element-wise comparison of 2 arrays; when
a.shape[0]is 2,minimum(a[0], a[1])is faster thanmin(a, axis=0).Examples
>>> import numpy as np >>> a = np.arange(4).reshape((2,2)) >>> a array([[0, 1], [2, 3]]) >>> np.min(a) # Minimum of the flattened array 0 >>> np.min(a, axis=0) # Minima along the first axis array([0, 1]) >>> np.min(a, axis=1) # Minima along the second axis array([0, 2]) >>> np.min(a, where=[False, True], initial=10, axis=0) array([10, 1])
>>> b = np.arange(5, dtype=float) >>> b[2] = np.nan >>> np.min(b) np.float64(nan) >>> np.min(b, where=~np.isnan(b), initial=10) 0.0 >>> np.nanmin(b) 0.0
>>> np.min([[-50], [10]], axis=-1, initial=0) array([-50, 0])
Notice that the initial value is used as one of the elements for which the minimum is determined, unlike for the default argument Python’s max function, which is only used for empty iterables.
Notice that this isn’t the same as Python’s
defaultargument.>>> np.min([6], initial=5) 5 >>> min([6], default=5) 6
- qredtea.symmetries.ibarrays.indarray(shape)[source]
Create integer array without initialization.
Arguments
- shapeints
Dimensions of the array.
- qredtea.symmetries.ibarrays.iones(shape)[source]
Create integer array of ones.
Arguments
- shapeints
Dimensions of the array.
- qredtea.symmetries.ibarrays.iproduct(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
Return the product of array elements over a given axis.
Parameters
- aarray_like
Input data.
- axisNone or int or tuple of ints, optional
Axis or axes along which a product is performed. The default, axis=None, will calculate the product of all the elements in the input array. If axis is negative it counts from the last to the first axis.
Added in version 1.7.0.
If axis is a tuple of ints, a product is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before.
- dtypedtype, optional
The type of the returned array, as well as of the accumulator in which the elements are multiplied. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.
- outndarray, optional
Alternative output array in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary.
- keepdimsbool, optional
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.
If the default value is passed, then keepdims will not be passed through to the prod method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.
- initialscalar, optional
The starting value for this product. See ~numpy.ufunc.reduce for details.
Added in version 1.15.0.
- wherearray_like of bool, optional
Elements to include in the product. See ~numpy.ufunc.reduce for details.
Added in version 1.17.0.
Returns
- product_along_axisndarray, see dtype parameter above.
An array shaped as a but with the specified axis removed. Returns a reference to out if specified.
See Also
ndarray.prod : equivalent method ufuncs-output-type
Notes
Arithmetic is modular when using integer types, and no error is raised on overflow. That means that, on a 32-bit platform:
>>> x = np.array([536870910, 536870910, 536870910, 536870910]) >>> np.prod(x) 16 # may vary
The product of an empty array is the neutral element 1:
>>> np.prod([]) 1.0
Examples
By default, calculate the product of all elements:
>>> import numpy as np >>> np.prod([1.,2.]) 2.0
Even when the input array is two-dimensional:
>>> a = np.array([[1., 2.], [3., 4.]]) >>> np.prod(a) 24.0
But we can also specify the axis over which to multiply:
>>> np.prod(a, axis=1) array([ 2., 12.]) >>> np.prod(a, axis=0) array([3., 8.])
Or select specific elements to include:
>>> np.prod([1., np.nan, 3.], where=[True, False, True]) 3.0
If the type of x is unsigned, then the output type is the unsigned platform integer:
>>> x = np.array([1, 2, 3], dtype=np.uint8) >>> np.prod(x).dtype == np.uint True
If x is of a signed integer type, then the output type is the default platform integer:
>>> x = np.array([1, 2, 3], dtype=np.int8) >>> np.prod(x).dtype == int True
You can also start the product with a value other than one:
>>> np.prod([1, 2], initial=5) 10
- qredtea.symmetries.ibarrays.isum(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
Sum of array elements over a given axis.
Parameters
- aarray_like
Elements to sum.
- axisNone or int or tuple of ints, optional
Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis.
Added in version 1.7.0.
If axis is a tuple of ints, a sum is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before.
- dtypedtype, optional
The type of the returned array and of the accumulator in which the elements are summed. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.
- outndarray, optional
Alternative output array in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary.
- keepdimsbool, optional
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.
If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.
- initialscalar, optional
Starting value for the sum. See ~numpy.ufunc.reduce for details.
Added in version 1.15.0.
- wherearray_like of bool, optional
Elements to include in the sum. See ~numpy.ufunc.reduce for details.
Added in version 1.17.0.
Returns
- sum_along_axisndarray
An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.
See Also
ndarray.sum : Equivalent method. add:
numpy.add.reduceequivalent function. cumsum : Cumulative sum of array elements. trapezoid : Integration of array values using composite trapezoidal rule.mean, average
Notes
Arithmetic is modular when using integer types, and no error is raised on overflow.
The sum of an empty array is the neutral element 0:
>>> np.sum([]) 0.0
For floating point numbers the numerical precision of sum (and
np.add.reduce) is in general limited by directly adding each number individually to the result causing rounding errors in every step. However, often numpy will use a numerically better approach (partial pairwise summation) leading to improved precision in many use-cases. This improved precision is always provided when noaxisis given. Whenaxisis given, it will depend on which axis is summed. Technically, to provide the best speed possible, the improved precision is only used when the summation is along the fast axis in memory. Note that the exact precision may vary depending on other parameters. In contrast to NumPy, Python’smath.fsumfunction uses a slower but more precise approach to summation. Especially when summing a large number of lower precision floating point numbers, such asfloat32, numerical errors can become significant. In such cases it can be advisable to use dtype=”float64” to use a higher precision for the output.Examples
>>> import numpy as np >>> np.sum([0.5, 1.5]) 2.0 >>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32) 1 >>> np.sum([[0, 1], [0, 5]]) 6 >>> np.sum([[0, 1], [0, 5]], axis=0) array([0, 6]) >>> np.sum([[0, 1], [0, 5]], axis=1) array([1, 5]) >>> np.sum([[0, 1], [np.nan, 5]], where=[False, True], axis=1) array([1., 5.])
If the accumulator is too small, overflow occurs:
>>> np.ones(128, dtype=np.int8).sum(dtype=np.int8) -128
You can also start the sum with a value other than zero:
>>> np.sum([10], initial=5) 15
- qredtea.symmetries.ibarrays.izeros(shape)[source]
Create integer array of zeros.
Arguments
- shapeints
Dimensions of the array.
Tooling for Abelian symmetries. For now, it is in qredtea as tooling for symmetries (open to move it somewhere else).
- class qredtea.symmetries.tooling_symmetry.LocalAbelianSymmetryInjector(sectors=None)[source]
Symmetry injector for usage with local symmetries or other setups, where more than a global projection is needed.
Arguments
- sectorsdict | None
If dictionary, contains key-value pairs with keys being tensor position in the network and values being
IrrepListingused as projector.
- inject_parse_sectors(params, sym)[source]
Parse sectors for symmetry and update symmetry if necessary.
Arguments
- paramsdict
Dictionary with simulation params, of interest are here the keys SymmetryTypes and Symmetries.
Returns
sym :
AbelianSymCombinedGroup- sectorsdict
Dictionary with positions as key and irreps as values.
Details
The position is hard-coded for the TTN at the moment.